package com.vv.tools.common.demo;

import com.fasterxml.jackson.databind.JsonNode;
import com.vv.tools.common.util.FileUtils;
import com.vv.tools.common.util.JsonUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import org.springframework.util.CollectionUtils;

/**
 * json转table
 *
 * @author wen.li
 */
public class JsonTableDemo {


    public static void main(String[] args) {
        JsonTableDemo jsonToTableDemo = new JsonTableDemo();
        jsonToTableDemo.run();
    }

    public void run() {
        String jsonStr = FileUtils.read(Objects.requireNonNull(FileUtils.getClassPathFile("demo/jsonTable.json")));
        printTable(Objects.requireNonNull(JsonUtil.readTreeForString(jsonStr)));
    }

    private void printTable(JsonNode jsonNode) {
        // 将jsonNode打印为表格, 第一行打印为表头
        List<String> headers = new ArrayList<>();
        for (JsonNode node : jsonNode) {
            Iterator<String> names = node.fieldNames();
            if (CollectionUtils.isEmpty(headers)) {
                while (names.hasNext()) {
                    String header = names.next();
                    System.out.print(header + "\t");
                    headers.add(header);
                }
                System.out.println();
            }
            for (String header : headers) {
                System.out.print(node.get(header).asText() + "\t");
            }
            System.out.println();
        }
    }

}
